import { login, UserInformation } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

const state = {
  token: getToken() || '',
  yonghuxx: {}
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  yonghu(state, data) {
    state.yonghuxx = data
  },
  removeToken(state) {
    removeToken()
    state.token = ''
  },
  removeProfile(state) {
    state.yonghuxx = {}
  }
}
const actions = {
  async login(store, data) {
    // 登录页应该将用户填写手机号和密码作为 data 传入
    const res = await login(data)
    store.commit('setToken', res.jwt)
    // 主动介入，登录时保存登录的时间戳，超时自动退出
    localStorage.setItem('loginTime', Date.now())
  },
  async getUserInfo(store) {
    const res1 = await UserInformation()
    store.commit('yonghu', res1)
  },

  // 退出清理数据
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    router.push('login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

